package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Constants;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.MammalFeature;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.IMammalFeatureService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/mammalFeature")
public class MammalFeatureController {

    @Resource
    private IMammalFeatureService mammalFeatureService;

    @Resource
    private ImageUploadService imageUploadService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody MammalFeature mammalFeature){
        //新增或更新
        return Result.success(mammalFeatureService.saveOrUpdate(mammalFeature));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(mammalFeatureService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(mammalFeatureService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(mammalFeatureService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(mammalFeatureService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<MammalFeature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(mammalFeatureService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName
    ) {
        QueryWrapper<MammalFeature> queryWrapper = new QueryWrapper<>();
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
        return Result.success(mammalFeatureService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<MammalFeature> list = mammalFeatureService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("chinese_outline", "中文目名");
        writer.addHeaderAlias("outline", "目名");
        writer.addHeaderAlias("chinese_section", "中文科名");
        writer.addHeaderAlias("section", "科名");
        writer.addHeaderAlias("chinese_name", "中文名");
        writer.addHeaderAlias("english_name", "英文名");
        writer.addHeaderAlias("nickname", "学名");
        writer.addHeaderAlias("literature_resources", "物种文献收录来源");
        writer.addHeaderAlias("protection_class", "保护级别");
        writer.addHeaderAlias("endemic_species", "特有种");
        writer.addHeaderAlias("chinese_threat", "濒危等级");
        writer.addHeaderAlias("weight", "体重");
        writer.addHeaderAlias("brain_capacity", "脑容量");
        writer.addHeaderAlias("length", "体长");
        writer.addHeaderAlias("tail_length", "尾长");
        writer.addHeaderAlias("forearm_length", "前臂长");
        writer.addHeaderAlias("hindfoot_length", "后足长");
        writer.addHeaderAlias("ear_length", "耳长");
        writer.addHeaderAlias("sexual_maturity", "性成熟时间");
        writer.addHeaderAlias("pregnancy_time", "妊娠时间");
        writer.addHeaderAlias("litter_size", "窝崽数");
        writer.addHeaderAlias("average_litter_size", "平均年窝数");
        writer.addHeaderAlias("generation_length", "世代长度");
        writer.addHeaderAlias("diet", "食性");
        writer.addHeaderAlias("activity_cycle", "活动模式");
        writer.addHeaderAlias("altitude_range", "海拔范围");
        writer.addHeaderAlias("habitat_type", "栖息地类型");
        writer.addHeaderAlias("habitat_width", "栖息地宽度");
        writer.addHeaderAlias("animal_geography", "动物地理界");
        writer.addHeaderAlias("biota", "生物群系");
        writer.addHeaderAlias("distribution_type", "分布型");
        writer.addHeaderAlias("geographical_zoning", "动物地理分区");
        writer.addHeaderAlias("province_river", "分布省份或水域");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("哺乳类特征表", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("中文目名", "chinese_outline");
        reader.addHeaderAlias("目名", "outline");
        reader.addHeaderAlias("中文科名", "chinese_section");
        reader.addHeaderAlias("科名", "section");
        reader.addHeaderAlias("中文名", "chinese_name");
        reader.addHeaderAlias("英文名", "english_name");
        reader.addHeaderAlias("学名", "nickname");
        reader.addHeaderAlias("物种文献收录来源", "literature_resources");
        reader.addHeaderAlias("保护级别", "protection_class");
        reader.addHeaderAlias("特有种", "endemic_species");
        reader.addHeaderAlias("濒危等级", "chinese_threat");
        reader.addHeaderAlias("体重", "weight");
        reader.addHeaderAlias("脑容量", "brain_capacity");
        reader.addHeaderAlias("体长", "length");
        reader.addHeaderAlias("尾长", "tail_length");
        reader.addHeaderAlias("前臂长", "forearm_length");
        reader.addHeaderAlias("后足长", "hindfoot_length");
        reader.addHeaderAlias("耳长", "ear_length");
        reader.addHeaderAlias("性成熟时间", "sexual_maturity");
        reader.addHeaderAlias("妊娠时间", "pregnancy_time");
        reader.addHeaderAlias("窝崽数", "litter_size");
        reader.addHeaderAlias("平均年窝数", "average_litter_size");
        reader.addHeaderAlias("世代长度", "generation_length");
        reader.addHeaderAlias("食性", "diet");
        reader.addHeaderAlias("活动模式", "activity_cycle");
        reader.addHeaderAlias("海拔范围", "altitude_range");
        reader.addHeaderAlias("栖息地类型", "habitat_type");
        reader.addHeaderAlias("栖息地宽度", "habitat_width");
        reader.addHeaderAlias("动物地理界", "animal_geography");
        reader.addHeaderAlias("生物群系", "biota");
        reader.addHeaderAlias("分布型", "distribution_type");
        reader.addHeaderAlias("动物地理分区", "geographical_zoning");

        reader.addHeaderAlias("分布省份或水域", "province_river");
        List<MammalFeature> list = reader.readAll(MammalFeature.class);
        mammalFeatureService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }
}
